package com.wondream.myframework.heima_concurrent;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 转账习题
 */
public class TransferTest {

    static Random random = new Random();

    public static int randomAmount() {
        return random.nextInt(800) + 1;
    }

    public static void main(String[] args) {
        Account account1 = new Account(1000);
        Account account2 = new Account(1000);
        multipyTransfer(account2, account1);
        multipyTransfer(account1, account2);
        System.out.println("最终总余额为：" + (account1.getMoney() + account2.getMoney()));
    }

    private static void multipyTransfer(Account account1, Account account2) {
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    account2.transfer(account1, 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public void transfer(Account target, int money) throws InterruptedException {
        synchronized (Account.class) {
            if (this.money >= money) {
                this.setMoney(this.getMoney() - money);
                target.setMoney(target.getMoney() + money);
            }
        }
    }
}
